package com.cskaoyan.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.dto.AllItemResponse;
import com.cskaoyan.mall.dto.ItemDto;
import com.cskaoyan.mall.search.api.ProductApi;
import com.cskaoyan.mall.search.converter.ProductConverter;
import com.cskaoyan.mall.search.entity.ItemDocument;
import com.cskaoyan.mall.search.repository.ProductRepository;
import com.cskaoyan.mall.search.service.InitDataService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @program: csmall-practice
 * @description:
 * @author: Lexis
 * @create: 2022-05-26 19:54
 **/

@Slf4j
@Service
public class InitDataServiceImpl implements InitDataService {

    @Autowired
    ProductRepository productRepository;

    @Autowired
    ProductApi productApi;

    @Autowired
    ProductConverter productConverter;

    @Override
    public void initItems() {
        try {

            AllItemResponse allProductItem = productApi.getAllProductItem();

            List<ItemDto> allItems = allProductItem.getAllItems();

            List<ItemDocument> itemDocuments = productConverter.items2Documents(allItems);

            productRepository.saveAll(itemDocuments);

            // // 将商品数据批量导入elasticsearch
            // BulkRequest bulkRequest = new BulkRequest();
            //
            // for (ItemDto item : allItems) {
            //     // 转化尾json字符串
            //     ItemDocument itemDocument = productConverter.item2Document(item);
            //
            //     String data = JSON.toJSONString(itemDocument);
            //
            //     IndexRequest indexRequest = new IndexRequest("tb_item").source(data, XContentType.JSON);
            //
            //     bulkRequest.add(indexRequest);
            // }
            //
            // response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            // log.info("插入+{}", response.status());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
